package com.yunshipei.core.common.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * 用于管理适配包和运行时配置信息的数据库，该数据库可能存在多个线程同时读写操作，为避免多线程导致的
 * 数据库读写错误，用来管理数据库的单例
 */
public class DBManager {

    private DBManager() {

    }

    private static final class DBManagerInner {
        private static final DBManager instance = new DBManager();
    }

    public static DBManager getInstance() {
        return DBManagerInner.instance;
    }

    private AdapterConfigDbHelper helper;
    private SQLiteDatabase mDB;
    private int count;

    public synchronized SQLiteDatabase openDB(Context context) {
        if (helper == null) {
            helper = new AdapterConfigDbHelper(context.getApplicationContext());
        }
        if (count == 0) {
            mDB = helper.getWritableDatabase();
        }
        count++;
        return mDB;
    }

    public synchronized void closeDB() {
        count--;
        if (count == 0) {
            mDB.close();
            mDB = null;
        }
    }
}
